package org.assistant.csp.utils;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.assistant.csp.data.Menu;

public class MenuUtils {
	protected static final Log log = LogFactory.getLog(MenuUtils.class);

	/**
	 * 将菜单数据转换成Tree结构的数据
	 * 
	 * @param menu
	 * @return
	 */
	public static Tree<Menu> convertMenu2Tree(List<Menu> menuList) {
		Tree<Menu> tree = new Tree<Menu>();

		for (int i = 0; i < menuList.size(); i++) {
			Menu menu = (Menu) menuList.get(i);
			int id = menu.getId();
			int parentId = menu.getParentId();
			int level = menu.getLevel();

			TreeNode<Menu> node = new TreeNode<Menu>(id, parentId, level);
			node.setNodeData(menu);

			if (level == 1) {
				tree.addParentTreeNode(node);
			} else {
				TreeNode<Menu> parent = tree
					.getParentTreeNodeByParent(parentId);
				addChild(parent, node);
			}
		}

		return tree;
	}

	/**
	 * 将子结点childNode添加到treeNode下
	 * 
	 * @param treeNode
	 * @param childNode
	 */
	private static void addChild(TreeNode<Menu> parentNode,
			TreeNode<Menu> childNode) {
		long childLevel = childNode.getLevel();

		if (parentNode != null) {
			if (parentNode.getId() == childNode.getParentId()) {
				parentNode.addChild(childNode);
				return;
			}
			if (--childLevel == parentNode.getLevel()) {
				if (parentNode.getId() == childNode.getParentId()) {
					parentNode.addChild(childNode);
				}
			} else if (childLevel > parentNode.getLevel()) {
				for (int i = 0; i < parentNode.childrenSize(); i++) {
					TreeNode<Menu> child = parentNode.getChild(i);
					addChild(child, childNode);
				}
			}
		}
	}
}
